﻿using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;


public class InputUI : MonoBehaviour
{

    [Header("实验配置")]
    public InputField inf_Duration;
    public InputField inf_Inv;
    public InputField inf_CountDownTime;
    public InputField inf_Frquency;
    public GameObject stimulusListPlane;
    public GameObject stimulusToggleGroup;

    public Text tex_ResourceLoadedStat;


    [Header("参与者信息")]
    public InputField inf_Index;
    public InputField inf_Name;
    public InputField inf_Age;

    public Toggle tog_MaleGender;
    public Toggle tog_ASD;

    private string stimulusGroupIdx;

    public void Start()
    {
        inf_CountDownTime.text = "3";
        inf_Frquency.text = "60"; //实际上30，怕电脑卡

        //Serializer.GetFromJson("F:\\Stimulus\\RawJsonData\\1_1_20220704_080740.json");
        //StartCoroutine(ResourceLoad());
    }


    public void OnStartBtnClicked()
    {
        if (inf_Duration.text != null && 
            inf_Inv.text != null && 
            inf_CountDownTime.text != null && 
            inf_Frquency.text != null && 
            inf_Age.text != null &&
            inf_Index.text != null &&
            inf_Name.text != null &&
            stimulusGroupIdx != null)
        {
            try
            {
                ProcessHandles.Cfg_Info.s_ImageDuration = float.Parse(inf_Duration.text);
                ProcessHandles.Cfg_Info.s_IntvDuration = float.Parse(inf_Inv.text);
                ProcessHandles.Cfg_Info.s_CountDown= int.Parse(inf_CountDownTime.text);
                ProcessHandles.Cfg_Info.s_Frequency = 30;//int.Parse(inf_Frquency.text);

                ProcessHandles.Participant_Info.s_Index = inf_Index.text;
                ProcessHandles.Participant_Info.s_Name = inf_Name.text;
                ProcessHandles.Participant_Info.s_Age = float.Parse(inf_Age.text);

                ProcessHandles.Participant_Info.s_IsMale = tog_MaleGender.isOn;
                ProcessHandles.Participant_Info.s_IsASD = tog_ASD.isOn;

                if(stimulusGroupIdx != ProcessHandles.Cfg_Info.s_StimulusGroupIdx)
                {
                    ProcessHandles.Cfg_Info.s_StimulusGroupIdx = stimulusGroupIdx;
                    ProcessHandles.Cfg_Info.s_StimulusList.Clear();
                    ProcessHandles.Cfg_Info.s_StimulusIdxList.Clear();

                    var d = stimulusGroupIdx.Split(' ');
                    string path = DataIO.stimulusBasePath + d[0] + "\\" + d[1];

                    if (path != null && path != string.Empty)
                    {
                        //Debug.Log(path.Length);
                        DirectoryInfo dir = new DirectoryInfo(path);

                        if (!dir.Exists)
                        {
                            //
                        }

                        FileInfo[] files = dir.GetFiles();

                        foreach (var f in files)
                        {
                            StartCoroutine(ResourceLoad(f.FullName));
                        }
                    }
                }



                var c = GetComponent<Controller>();
                c.enabled = true;
                c.Init();

            }
            catch
            {
                //ProcessHandles.Cfg_Info.s_ImageDuration = 10f;
                //ProcessHandles.Cfg_Info.s_IntvDuration = 2f;
            }

        }
        else
        {
            Debug.Log("fail");
        }

    }

    public void OnResourceReloadBtnClicked()
    {
        SwitchActiveOfStimulusPlane();
    }

    public void OnDefaultCfgBtnCilcked()
    {
        inf_Duration.text = "3";
        inf_Inv.text = "1";
        inf_CountDownTime.text = "3";
        inf_Frquency.text = "60";

        stimulusGroupIdx = "A-Action 00";
        tex_ResourceLoadedStat.text = "A-Action 00";

        inf_Index.text = "1";
        inf_Name.text = "1";
        inf_Age.text = "1";
    }

    public void OnEnableCheckResultBtnClicked()
    {
        string jsonPath = FileDialog.OpenFile();

        if (File.Exists(jsonPath))
        {
            Serializer.GetFromJson(jsonPath);
            DataIO.handlingPath = jsonPath;
            StartCoroutine(ResourceLoad());
        }


    }

    public void OnAutoSetStimulusBtnClicke()
    {
        if(Serializer.records == null)
        {
            Serializer.LoadRecords();
        }

        if (inf_Index.text != "")
        {
            bool allParticipated = false;
            foreach(var re in Serializer.records)
            {
                if (re.particippatedList.Contains(inf_Index.text)) continue;
                else
                {
                    stimulusGroupIdx = re.s_StimulusGroupIdx;
                    tex_ResourceLoadedStat.text = re.s_StimulusGroupIdx;
                    allParticipated = true;
                    break;
                }
            }
            if (allParticipated)
            {

            }
        }
    }

    IEnumerator ResourceLoad(string path)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(path);

        yield return request.SendWebRequest();

        if (request.isHttpError || request.isNetworkError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Texture tt = DownloadHandlerTexture.GetContent(request);
            ProcessHandles.Cfg_Info.s_StimulusList.Add
                (Sprite.Create((Texture2D)tt, new Rect(0, 0, tt.width, tt.height), new Vector2(0.5f, 0.5f)));

            int startPos = path.LastIndexOf('\\') + 1;

            ProcessHandles.Cfg_Info.s_StimulusIdxList.Add
                (path.Substring(startPos, path.LastIndexOf('.') - startPos));

            //Debug.Log(path.Substring(startPos, path.LastIndexOf('.') - startPos));
        }
    }

    IEnumerator ResourceLoad()
    {
        for(int i = 0; i < Serializer.serializableCfgInfo.s_StimulusIdxList.Count; i++)
        {
            var sp = Serializer.serializableCfgInfo.s_StimulusGroupIdx.ToString().Split(' ');

            string path = DataIO.stimulusBasePath
                + sp[0] + "\\" + sp[1] + "\\" + Serializer.serializableCfgInfo.s_StimulusIdxList[i];

            path += (File.Exists(path + ".jpg") ? ".jpg" : ".jpeg");
            

            Debug.Log(path);

            UnityWebRequest request = UnityWebRequestTexture.GetTexture(path);

            yield return request.SendWebRequest();

            if (request.isHttpError || request.isNetworkError)
            {
                Debug.Log(request.error);
            }
            else
            {
                Texture tt = DownloadHandlerTexture.GetContent(request);
                ProcessHandles.Cfg_Info.s_StimulusList.Add
                    (Sprite.Create((Texture2D)tt, new Rect(0, 0, tt.width, tt.height), new Vector2(0.5f, 0.5f)));
            }
        }

        SceneManager.LoadScene(1);
    }

    public void SwitchActiveOfStimulusPlane()
    {
        if (stimulusListPlane.activeSelf)
        {
            foreach(Transform t in stimulusToggleGroup.transform)
            {
                if (t.GetComponent<Toggle>().isOn)
                {
                    stimulusGroupIdx = t.Find("Label").GetComponent<Text>().text;

                    tex_ResourceLoadedStat.text = stimulusGroupIdx;
                    break;
                }
            }
        }

        stimulusListPlane.SetActive(!stimulusListPlane.activeSelf);
    }
}



